import pymysql


# 定义数据库工具类
class DBTools():
    # 创建连接-类方法:可以直接使用类名调用!
    @classmethod
    def __create_con(cls):
        conn = pymysql.connect(host="127.0.0.1",
                               user="root",
                               password="root",
                               port=3306,
                               database="test",
                               charset="utf8")
        return conn

    # 查一条记录,封装为类方法,方便调用
    @classmethod
    def query_one(cls, sql):
        conn = None
        curs = None
        resp = None
        try:
            # 创建连接
            conn = DBTools.__create_con()
            # 获取游标对象
            curs = conn.cursor()
            # 执行查询SQL
            curs.execute(sql)
            # 提取一条记录
            resp = curs.fetchone()
        except Exception as e:
            print("查询结果失败:", str(e))
        finally:
            # 关闭游标
            curs.close()
            # 关闭连接
            conn.close()
            return resp

    # 执行增删改语句,封装为类方法,方便调用
    @classmethod
    def uid_tools(cls, sql):
        conn = None
        curs = None
        try:
            conn = DBTools.__create_con()
            curs = conn.cursor()
            curs.execute(sql)
            print("生效条数:", conn.affected_rows())
            conn.commit()
        except Exception as e:
            print("执行语句失败:", str(e))
            conn.rollback()
        finally:
            curs.close()
            conn.close()


if __name__ == '__main__':
    print(DBTools.query_one("select * from books;"))








